<?php
/**
 * Created by PhpStorm.
 * User: jiangtaiping
 * Date: 2017/2/23
 * Time: 14:57
 */
class Controller_Adminmall_Manager extends Controller_Adminmall_Abstract
{
    /*
     * 数据库
     */
    private $DBServer = "xhs_slave";
    /**
     * @var array $account_type 后台账号类型
     */
    private $account_type = array();
    /**
     * @var array $status_type 代理账号审核状态类型
     */
    private $revice_status_type = array();
    /**
     * @var array $status_type 账号状态类型
     */
    private $status_type = array();

    private $edit_account_type = 0;

    public function __construct()
    {
        parent::__construct();
        $this->revice_status_type = FConfig::get('type.revice_status_type');
        $this->status_type = FConfig::get('type.account_status_type');
        $this->account_type = FConfig::get('type.account_type');
    }

    /**
     * 显示用户列表
     */
    public function defaultAction()
    {
//        $this->openDebug();
        $page = FRequest::getInt('page');
        $w = trim(FRequest::getString('keyword'));
        $isadmin = FRequest::getInt('isadmin');
        $status = FRequest::getInt('status');
        $gid = FRequest::getInt('gid');
        $where = array(
            'm.status'=>array('lt'=>9)
        );

        if ($w) {
            if (preg_match('#^\d+$#', $w)) {
                $where['m.uid']=$w;
            } else {
                $where['m.username']=array('like'=>$w);
            }
        }
        if ($gid) {
            $where['m.groupid']=$gid;
        }
        if ($isadmin) {
            $where['m.isadmin']=$isadmin;
        }
        if ($status && $status < 9) {
            $where['m.status']=$status;
        }

        $managerTable = new FTable('manager', 'm', $this->DBServer);
        $managerList = $managerTable->fields("m.*, cs.name as shop_name")
            ->leftJoin("chain_shop", "cs", "cs.id=m.shop_id")
            ->page($page)
            ->where($where)
            ->order(array('m.uid' => 'asc'))
            ->limit(30)
            ->select();
        $pagerInfo = $managerTable->getPagerInfo();
        /**
         * 获取用户组提供选择查询
         */
        $groupTable = new  FTable('manager_group', '', $this->DBServer);
        $groupList = $groupTable->fields('id,title')->select();
        $group_list = array();
        foreach ($groupList as $v){
            $group_list[$v['id']] = $v['title'];
        }

        /*
         * 获取连锁店提供选择查询
         */
        /*$shopTable = new  FTable('chain_shop', '', $this->DBServer);
        $shopList = $shopTable->fields('id,name')->select();
        $this->assign('shopList', $shopList);
        foreach ($groupList as $v){
            $group_list[$v['id']] = $v['name'];
        }*/


        foreach ($managerList as $key=>$v){
            $managerList[$key]['groupname'] = isset($group_list[$v['groupid']]) ? $group_list[$v['groupid']] : '未分配';
        }
        $this->assign('groupList', $group_list);
        $this->assign('page_info', $pagerInfo);
        $this->assign('managerList', $managerList);
        $this->assign('status_type', $this->status_type);
        $this->assign('account_type', $this->account_type);

        /**
         * 配置权限访问
         */
        $this->assign('modify_user',Service_ManagerMall::checkRole('/adminmall/manager/modify'));
        $this->assign('delete_user',Service_ManagerMall::checkRole('/adminmall/manager/delete'));

        $this->display('adminmall/manager/list');
    }

    /**
     * 添加/更新管理员信息
     */
    public function modifyAction(){
        global $_F;
        $id = FRequest::getInt('id');
        $managerTable = new FTable('manager', '', $this->DBServer);
        $userInfo = array();
        $action = 'manager_add';
        $comment = '添加后台账号：';
        $formUrl = '/manager/modify';
        if($this->edit_account_type == 1){
            $formUrl = '/manager/operate';
        }
        if($id){
            $userInfo = $managerTable->where(array('uid'=>$id))->find();
            if(!$userInfo){
                $id = 0;
            }else{
                $action = 'manager_edit';
                $comment = '修改后台账号：';
                $formUrl .= '?id='.$id;
            }
        }
        if ($this->isPost()) {
            $uid = $_F['uid'];
            $truename = FRequest::getPostString('truename');
            $username = FRequest::getPostString('username');
            $mobile = FRequest::getPostString('mobile');
            $isadmin = FRequest::getPostInt('isadmin');
            $groupid = FRequest::getPostInt('groupid');
            $status = FRequest::getPostInt('status');
            $password = FRequest::getPostString('password');
            $parent_id = FRequest::getPostInt('parent_id');
            $re_password = FRequest::getPostString('re_password');
            $shop_id = FRequest::getPostInt('shop_id') ? FRequest::getPostInt('shop_id') : 0;
            if (trim($username) == '') {
                $this->error('用户名不能为空！', $formUrl);
            }
            $data = array(
                'create_time'=>time(),
                'mobile'=>$mobile,
                'username'=>$username,
                'truename'=>$truename,
                'isadmin'=> 1,
                'groupid'=>$groupid,
                'status'=> 1,
                'parent_id'=>$parent_id,
                'shop_id'=>$shop_id,
            );
            if($this->edit_account_type == 1){
                $data['isadmin'] = 2;
            }
            if(!$userInfo){
                if ($password == '' || strlen($password) < 6) {
                    $this->error('密码安全性太弱！', $formUrl);
                }
            }
            if($password != ""){
                if($password != $re_password){
                    $this->error('两次密码不一致!',$formUrl);
                }
                $data['password'] = Service_ManagerMall::getEncryptPassword($password);
            }

            $checkWhere = array(
                'username'=>$username,
                'status'=>array('lt'=>9)
            );
            if($id > 0){
                $checkWhere['uid']=array('neq'=>$id);
            }

            $checkUserName = $managerTable->fields('username')->where($checkWhere)->find();
            if ($checkUserName) {
                $this->error('用户名重复！', $formUrl);
            }

            $comment .= $username;

            $managerTable = new FTable('manager', '', 'slave_master');
            if($id <= 0){
                $result = $managerTable->insert($data,$comment);
            }else{
                $result = $managerTable->where(array('uid'=>$id))->update1($data);
            }
            if ($result) {
                //添加成功日志
                FLogger::write(array('action_uid' => $uid, 'ip' => FRequest::getClientIP(), 'manager' => $data), 'manager_add');
                Service_ManagerMall::addManagerLog($action,$comment);
                $go_url = '/adminmall/manager/default';
                if($this->edit_account_type == 1){
                    $go_url = '/adminmall/main/operate';
                }
                $this->success(($id > 0 ? '修改' : '添加').'成功！', $go_url);
            }else{
                $this->error('操作失败');
            }
        }

        if($id > 0 && $userInfo){
            $this->assign('info',$userInfo);
        }else{
            $this->assign('info',array(
                'isadmin'=>2,
                'status'=>1,
                'groupid'=>2
            ));
        }

        /*
         * 获取连锁店提供选择
         */
        $shopTable = new  FTable('chain_shop', '', $this->DBServer);
        $shopList = $shopTable->fields('id,name')->select();
        $this->assign('shopList', $shopList);

        /**
         * 获取用户组提供选择
         */
        $groupTable = new  FTable('manager_group', '', $this->DBServer);
        $groupList = $groupTable->fields('id,title')->select();
        $this->assign('groupList', $groupList);
        $this->assign('account_type',$this->account_type);
        $this->assign('status_type',$this->status_type);
        $this->assign('revice_status_type',$this->revice_status_type);
        $this->assign('edit_account_type',$this->edit_account_type);
        $this->assign('formUrl',$formUrl);
        $this->display('adminmall/manager/modify');
    }

    /**
     * 运营账号单独管理
     */
    public function operateAction(){
        $this->edit_account_type = 1;
        $this->modifyAction();
    }

    /**
     * 删除管理员账号
     */
    public function deleteAction(){
        $id = FRequest::getInt('id');
        if($id){
            $managerTable = new FTable('manager', '', 'xhs_master');
            $managerTable->where(array('uid'=>$id))->update1(array('status'=>9));
            Service_ManagerMall::addManagerLog('manager_delete','删除后台账号：'.$id);
            $this->success('删除用户成功！','/manager/default');
        }else{
            $this->error('error');
        }
    }

    /**
     * 管理员组列表
     */
    public function groupAction(){
        $page = FRequest::getInt('page');
        $w = trim(FRequest::getString('keyword'));
        $where = array(
            'status'=>array('lt'=>9)
        );

        if ($w) {
            $where['title']=array('like'=>$w);
        }

        $groupTable = new FTable('manager_group', '', $this->DBServer);
        $groupList = $groupTable->page($page)->where($where)->order(array('id' => 'asc'))->limit(30)->select();
        $pagerInfo = $groupTable->getPagerInfo();
        $this->assign('page_info', $pagerInfo);
        $this->assign('groupList', $groupList);

        $this->display('adminmall/manager/group');
    }

    /**
     * 管理员组修改/新增
     */
    public function groupmodifyAction(){
        $id = FRequest::getInt('id');
        $groupTable = new FTable('manager_group', '', $this->DBServer);
        $groupInfo = array();
        $action = 'manager_group_add';
        $comment = '添加用户组：';
        $formUrl = '/adminmall/manager/groupmodify';
        if($id){
            $groupInfo = $groupTable->where(array('id'=>$id))->find();
            if(!$groupInfo){
                $id = 0;
            }else{
                $action = 'manager_group_edit';
                $comment = '修改用户组：';
                $formUrl .= '?id='.$id;
            }
        }
        if ($this->isPost()) {
            $title = FRequest::getPostString('title');
            $permission = FRequest::getPostString('permission');
            if (trim($title) == '') {
                $this->error('名称不能为空！', $formUrl);
            }
            if(!is_array($permission) || $permission == ''){
                $permission = array();
            }
            $permission = serialize($permission);

            $checkWhere = array(
                'title'=>$title
            );
            if($id > 0){
                $checkWhere['id']=array('neq'=>$id);
            }

            $checkGroup = $groupTable->fields('title')->where($checkWhere)->find();
            if ($checkGroup) {
                $this->error('用户组名称重复！', $formUrl);
            }

            $comment .= $title;
            $groupTable = new FTable('manager_group', '', 'xhs_master');
            if($id <= 0){
                $result = $groupTable->insert(array('title'=>$title,'permission'=>$permission),$comment);
                $id = $result;
            }else{
                $result = $groupTable->where(array('id'=>$id))->update1(array('title'=>$title,'permission'=>$permission));
            }
            if ($result) {
                Service_ManagerMall::clearGroupRole($id);
                Service_ManagerMall::addManagerLog($action,$comment);
                $this->success(($id > 0 ? '修改' : '新增').'成功！', '/adminmall/manager/group');
            }else{
                $this->error('新增用户组失败');
            }
        }
        if($id > 0 && $groupInfo){
            if($groupInfo['permission'] != ""){
                $groupInfo['permission'] = unserialize($groupInfo['permission']);
            }else{
                $groupInfo['permission'] = array();
            }
            $this->assign('info',$groupInfo);
        }
        $this->assign('formUrl',$formUrl);
        $this->assign('permission',FConfig::get('permission.manager_xhs'));

        $this->display('adminmall/manager/group-modify');
    }

    /**
     * 删除管理员组
     */
    public function groupdeleteAction(){
        $id = FRequest::getInt('id');
        if($id){
            /**
             * 如果还有用户属于这个管理组的，不允许删除
             */
            $managerTable = new FTable('manager', '', $this->DBServer);
            $managerList = $managerTable->fields('uid')->where(array('groupid'=>$id))->find();
            if($managerList){
                $this->error('还有用户属于该组，不允许删除');
            }
            $groupTable = new FTable('manager_group', '', 'xhs_master');
            $groupTable->where(array('id'=>$id))->update1(array('status'=>9));
            Service_ManagerMall::addManagerLog('manager_group_delete','删除后台用户组：'.$id);
            $this->success('删除用户组成功！','/adminmall/manager/group');
        }else{
            $this->error('error');
        }
    }
}
